//
//  BuzzerController.cpp
//  QuizMaster
//
//  Created by Jeppe Nielsen on 3/24/15.
//  Copyright (c) 2015 Jeppe Nielsen. All rights reserved.
//

#include "BuzzerDevice.hpp"

BuzzerDevice::BuzzerDevice() : frameCounter(0), input(0) {

}

BuzzerDevice::~BuzzerDevice() {
    Unbind();
}

void BuzzerDevice::Bind(BigButtonManager* input) {
    this->input = input;
    this->input->ButtonDown += event_handler(this, &BuzzerDevice::ButtonDown);
    buzzersThisFrame.clear();
}

void BuzzerDevice::Unbind() {
    if (input) {
        input->ButtonDown -= event_handler(this, &BuzzerDevice::ButtonDown);
    }
    buzzersThisFrame.clear();
}

void BuzzerDevice::ButtonDown(BigButtonEvent e) {
    Buzzers::iterator it = buzzers.find(e.PlayerIndex);
    if (it == buzzers.end()) return;
    if (!it->second.enabled) return;
    buzzersThisFrame.push_back(it->second.index);
}

void BuzzerDevice::Update(float dt) {
    if (buzzersThisFrame.empty()) return;
    OnBuzz(buzzersThisFrame[0]);
    buzzersThisFrame.clear();
}

void BuzzerDevice::AddBuzzer(int playerIndex, int buzzerIndex) {
    Buzzer& b = buzzers[buzzerIndex];
    b.index = playerIndex;
    b.enabled = true;
}

void BuzzerDevice::DisableBuzzer(int playerIndex) {
    for (Buzzers::iterator it=buzzers.begin(); it!=buzzers.end(); ++it) {
        if (it->second.index == playerIndex) {
            it->second.enabled = false;
        }
    }
}

void BuzzerDevice::AllowAll() {
    for (Buzzers::iterator it=buzzers.begin(); it!=buzzers.end(); ++it) {
        it->second.enabled = true;
    }
}